package http

import (
	"http"
	"template"
	"gocase/config"
	"io/ioutil"
)

var templates = map[string]*template.Template{
	"main": nil,
}

func loadTemplates() {
	for k, _ := range templates {
		t := template.New(nil)
		t.SetDelims("#{", "}#")
		t.ParseFile("files/" + k + ".html")
		templates[k] = t
	}
}

func exec(tname string, w http.ResponseWriter, data interface{}) {
	if config.Debug {
		loadTemplates()
	}
	templates[tname].Execute(w, data)
}

func mainHandler(w http.ResponseWriter, req *http.Request) {
	exec("main", w, nil)
}

func fileHandler(w http.ResponseWriter, req *http.Request) {
	fname := req.FormValue("name")
	b, err := ioutil.ReadFile("files/" + fname)
	if err != nil {
		http.NotFound(w, req)
		return
	}
	w.Write(b)
}

func Serve() {
	loadTemplates()
	http.HandleFunc("/", mainHandler)
	http.HandleFunc("/file", fileHandler)
	http.ListenAndServe(":80", nil)
}
